import { UPLOADER_IAMGE_LETTER_THAN } from '@/constants';
import dayjs, { Dayjs } from 'dayjs';

// 格式化行业响应值
export function formatTreeData2(data: any) {
  function format(arr: any) {
    return arr.map((t: any) => ({
      ...t,
      isLeaf: Number(t.storey) === 4 || t.childes.length <= 0 ? true : false,
      children: format(t.childes),
      key: t.code,
      title: t.name,
      childes: null,
      value: t.code,
    }));
  }
  return format(data);
}

export function treeFindPath(tree: any[], func: any, path: any = []): any {
  if (!tree) return [];
  for (const data of tree) {
    path.push(data.code);
    if (func(data)) return path;
    if (data.children) {
      const findChildren = treeFindPath(data.children, func, path);
      if (findChildren.length) return findChildren;
    }
    path.pop();
  }
  return [];
}

// 数组转树
export const array2Tree = (
  list: any,
  parentId: any,
  key = 'id',
  parentIdKey = 'parentId',
) => {
  function loop(parId: any) {
    return list.reduce((acc: any, cur: any) => {
      delete cur.isLeaf;
      if (cur[parentIdKey] == parId) {
        cur.children = loop(cur[key]);
        acc.push(cur);
      }
      return acc;
    }, []);
  }
  return loop(parentId);
};

// 计算行业薪资
export function makeUnitStr(item: any) {
  return `${item?.minSalary ? (item.minSalary >= 10 ? item.minSalary / 10 + '万' : item.minSalary + '千') : '-'}-${
    item?.maxSalary ? (item.maxSalary >= 10 ? item.maxSalary / 10 + '万' : item.maxSalary + '千') : '-'
  }`;
}

// 计算百分比，保留两位小数
export function makePercent(b: any) {
  return b ? (b * 100).toFixed(2) : '';
}
// 计算百分比，不保留小数
export function makePercentZero(b: any) {
  return b ? (b * 100).toFixed(0) : '';
}
export function NottoFixed(b: any) {
  return b ? (b * 10).toFixed(0) : '';
}

// 重写部分树结构 disabled 字段
export function disabledTreeData(tree: any) {
  function loop(_d: any) {
    _d.forEach((t: any) => {
      if (t.children && t.children?.length) {
        t.disabled = true;
        loop(t.children);
      }
    });
  }
  loop(tree);
}

export function fileLt5M(file: any) {
  return file.size / 1024 / 1024 < UPLOADER_IAMGE_LETTER_THAN;
}

export function fileLt20M(file: any) {
  return file.size / 1024 / 1024 < 20;
}

export function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

// export function fileLt10M(file: any) {
//   return file.size / 1024 / 1024 < UPLOADER_RESUME_LETTER_THAN;
// }

export function convertRes2Blob(response: any, _filename?: string | null) {
  if (!response?.data?.size) return;
  // 提取文件名
  const filename =
    _filename ||
    response.headers['content-disposition']?.match(/filename=(.*)/)[1];
  // 将二进制流转为blob
  const blob = new Blob([response.data], { type: 'application/octet-stream' });
  // 创建新的URL并指向File对象或者Blob对象的地址
  const blobURL = window.URL.createObjectURL(blob);
  // 创建a标签，用于跳转至下载链接
  const tempLink = document.createElement('a');
  tempLink.style.display = 'none';
  tempLink.href = blobURL;
  tempLink.setAttribute('download', decodeURI(filename));
  // 兼容：某些浏览器不支持HTML5的download属性
  if (typeof tempLink.download === 'undefined') {
    tempLink.setAttribute('target', '_blank');
  }
  // 挂载a标签
  document.body.appendChild(tempLink);
  tempLink.click();
  document.body.removeChild(tempLink);
  // 释放blob URL地址
  window.URL.revokeObjectURL(blobURL);
}

// 用户出生年月限制
export function disabledUserAgeDate(current: Dayjs) {
  return (
    current &&
    (current > dayjs(1293811199000) || current < dayjs(-315648000000))
  );
}

// 用户参加工作日期限制
export function disabledDateWorkStartYear(current: Dayjs) {
  return current && (current > dayjs() || current < dayjs(-315648000000));
}

export const aImageFallback = ``;

export function getWsProtocol() {
  const proto = window.location.protocol;
  if (proto.indexOf('https') > -1) return `wss://`;
  return `wss://`;
}

export function sleep(s: number) {
  return new Promise(resolve => {
    setTimeout(() => resolve(void 0), s);
  });
}

// 富文本反转义html (从接口取值后调用方法转为 Html)，v-html="escape2Html(text)"
export const escape2Html = (str: string) => {
  const arrEntities: any = { lt: '<', gt: '>', nbsp: ' ', amp: '&', quot: '"' };
  return str?.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all, t) {
    return arrEntities[t];
  });
};

// 提取富文本标签中的纯文字
export const getTxtFromFullText = (html: string) => {
  //匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
  const re1 = new RegExp('<.+?>', 'g');

  return html.replace(re1, '');
};

export function _setInterval(fn: () => void, millisec: number, count?: number) {
  let timer: NodeJS.Timeout;
  function interval() {
    if (typeof count === 'undefined' || count-- > 0) {
      timer = setTimeout(interval, millisec);
      try {
        fn();
      } catch (e: any) {
        count = 0;
        throw e.toString();
      }
    }
  }
  timer = setTimeout(interval, millisec);
  return {
    callback: () => clearTimeout(timer),
  };
}

export function generateLogo(text = '') {
  const cvs = document.createElement('canvas');
  text = text.substring(0, 2);
  cvs.setAttribute('width', '200px');
  cvs.setAttribute('height', '200px');
  const ctx = cvs.getContext('2d')!;
  ctx.fillStyle = '#fff';
  ctx.fillRect(0, 0, 200, 200);
  ctx.fillStyle = '#1890ff';
  ctx.font = 200 * 0.4 + 'px Arial';
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'center';
  ctx.fillText(text, 200 / 2, 200 / 1.9);
  return cvs.toDataURL('image/jpeg', 1);
}

export function formatNumber(number: any) {
  number = number * 1000;

  if (number >= 10000) {
    const num = (number / 10000).toFixed(1); // 将数字除以10000得到万的数量
    return num + '万';
  } else {
    const num = (number / 1000).toFixed(0); // 将数字除以1000得到千的数量
    return num + '千';
  }

  // console.log(formatNumber(5000));    // 输出：5千
  // console.log(formatNumber(15000));   // 输出：1.5万
  // console.log(formatNumber(123456));  // 输出：12.3万
}

export function parseNumber(str: any) {
  let num = 0;
  if (str.includes('千')) {
    num = parseFloat(str) * 1000; // 将带有"千"单位的字符串转换为数字
  } else if (str.includes('万')) {
    num = parseFloat(str) * 10000; // 将带有"万"单位的字符串转换为数字
  } else {
    num = parseFloat(str); // 没有单位的情况，直接转换为数字
  }

  return (num / 1000).toFixed(1);
}
